<?php

namespace app\api\controller\customer;

use app\api\controller\Api;
use app\common\customer\model\Customer;
use app\common\customer\model\CustomerBanquet;
use app\common\customer\validate\CustomerProductValidate;
use think\db\exception\DbException;

class Product extends Api
{
    public function read()
    {
        $post = $this->request->post();

        // 获取意向产品
        $productModel = new CustomerBanquet();
        $products = $productModel->where('member_id', $post['id'])->select();
        foreach ($products as $row) {
            $row->append(['category', 'creator', 'city', 'tag']);
        }
        $result['products'] = $products;

        return success($result);
    }

    public function save()
    {
        $post = $this->request->post();

        $validate = new CustomerProductValidate();
        if (!$validate->scene('create')->check($post)) {
            return error([], $validate->getError());
        }

        $productModel = new CustomerBanquet();
        if (!empty($post['id'])) {
            // 更新
            $productModel->startTrans();
            try {
                $row = $productModel->where('id', $post['id'])->find();
                $row->save($post);

                $productModel->commit();
            } catch (DbException $e) {
                $productModel->rollback();
                return error([], $e->getMessage());
            }
        } else {
            // 新增
            if (empty($post['member_id'])) {
                return error([], "参数错误");
            }

            $productModel->startTrans();
            try {
                $row = new CustomerBanquet();
                $row->save($post);

                $productModel->commit();
            } catch (DbException $e) {
                $productModel->rollback();
                return error([], $e->getMessage());
            }
        }

        return success([], "更新成功");
    }
}